package controllers

import (
	"2021-06-12/config"
	"2021-06-12/models"
	"2021-06-12/tools"
	"encoding/json"
	"fmt"
	"net/http"
	"strings"

	"github.com/astaxie/beego"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) GetAccessToken() string {
	// 拼接请求
	appID := config.WeAccessToken.AppID
	secret := config.WeAccessToken.Secret
	CodeToSessURL := config.WeAccessToken.CodeToSessURL
	CodeToSessURL = strings.Replace(CodeToSessURL, "{appid}", appID, -1)
	CodeToSessURL = strings.Replace(CodeToSessURL, "{secret}", secret, -1)

	resp, err := http.Get(CodeToSessURL)
	// 请求数据返回异常处理
	if err != nil {
		c.Data["json"] = &map[string]interface{}{
			"errNo": models.ErrorCode.ERROR,
			"msg":   err,
		}
		return ""
	}

	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		c.Data["json"] = &map[string]interface{}{
			"errNo": models.ErrorCode.ERROR,
			"msg":   err,
		}
		return ""
	}

	var data map[string]interface{}
	err = json.NewDecoder(resp.Body).Decode(&data)
	// 解析异常处理
	if err != nil {
		c.Data["json"] = &map[string]interface{}{
			"errNo": models.ErrorCode.ERROR,
			"msg":   err,
		}
		return ""
	}

	c.Data["json"] = &map[string]interface{}{
		"errNo": models.ErrorCode.SUCCESS,
		"msg":   "success",
		"data":  &data,
	}
	return data["access_token"].(string)
}

func (c *UserController) Login() {
	code := c.GetString("code")
	referCode := c.GetString("referCode")
	fmt.Println("code:", code)
	// code异常处理
	if code == "" {
		c.Data["json"] = &map[string]interface{}{
			"errNo": models.ErrorCode.ERROR,
			"msg":   "参数code错误",
		}
		c.ServeJSON()
		return
	}
	// 拼接请求
	appID := config.WeAppConfig.AppID
	secret := config.WeAppConfig.Secret
	CodeToSessURL := config.WeAppConfig.CodeToSessURL
	CodeToSessURL = strings.Replace(CodeToSessURL, "{appid}", appID, -1)
	CodeToSessURL = strings.Replace(CodeToSessURL, "{secret}", secret, -1)
	CodeToSessURL = strings.Replace(CodeToSessURL, "{code}", code, -1)

	resp, err := http.Get(CodeToSessURL)
	// 请求数据返回异常处理
	if err != nil {
		c.Data["json"] = &map[string]interface{}{
			"errNo": models.ErrorCode.ERROR,
			"msg":   err,
		}
		c.ServeJSON()
		return
	}

	defer resp.Body.Close()
	// 返回数据异常处理
	if resp.StatusCode != 200 {
		c.Data["json"] = &map[string]interface{}{
			"errNo": models.ErrorCode.ERROR,
			"msg":   err,
		}
		c.ServeJSON()
		return
	}

	var data map[string]interface{}
	err = json.NewDecoder(resp.Body).Decode(&data)
	// 解析异常处理
	if err != nil {
		c.Data["json"] = &map[string]interface{}{
			"errNo": models.ErrorCode.ERROR,
			"msg":   err,
		}
		c.ServeJSON()
		return
	}
	// 是否存在session_key
	if _, ok := data["session_key"]; !ok {
		c.Data["json"] = &map[string]interface{}{
			"errNo": models.ErrorCode.ERROR,
			"msg":   "session_key 不存在",
		}
		c.ServeJSON()
		return
	}
	// 正确解析
	fmt.Println(data)
	openID := data["openid"].(string)
	sessionKey := data["session_key"].(string)

	c.SetSession("weAppOpenID", openID)
	c.SetSession("weAppSessionKey", sessionKey)

	// 获取access_token
	// 查找是否存在用户
	u, err := models.GetUserByOpenId(openID)
	if err != nil {
		fmt.Printf("%s", err)
		// 没有查找到对应的用户则插入记录
		// 插入之前先对数据进行处理
		if referCode != "" {
			referUser, err := models.GetUserByCode(referCode)
			if err != nil {
				fmt.Println(err)
				// 添加查找邀请人错误
				c.Data["json"] = &map[string]interface{}{
					"errNo": models.ErrorCode.ERROR,
					"msg":   "邀请人不存在",
				}
				c.ServeJSON()
				return
			}

			if referUser.OpenId == "" {
				c.Data["json"] = &map[string]interface{}{
					"errNo": models.ErrorCode.ERROR,
					"msg":   "邀请人不存在",
				}
				c.ServeJSON()
				return
			}

			referUser.ReferNum += 1
			numCode, err := models.UpdateUserForPhone(&referUser)
			fmt.Println(numCode, err)

			u.ReferCode = referCode // 邀请人的邀请码
		}

		u.Label = "YXJ" // 所属企业label

		count, err := models.AddUser(&u)
		fmt.Println(count, err)
		if err != nil {
			c.Data["json"] = &map[string]interface{}{
				"errNo": models.ErrorCode.ERROR,
				"msg":   err,
			}
			c.ServeJSON()
			return
		}
	}

	dbUser, err := models.GetUserByOpenId(openID)
	if err != nil {
		fmt.Printf("%s", err)
	}
	c.Data["json"] = &map[string]interface{}{
		"errNo": models.ErrorCode.SUCCESS,
		"msg":   "success",
		"data":  &dbUser,
	}
	c.ServeJSON()
}

// SetWeAppUserInfo 设置小程序用户加密信息
func (c *UserController) SetUserInfo() {
	iv := c.GetString("iv")
	encryptedData := c.GetString("encryptedData")
	code := c.GetString("code")

	appID := config.WeAppConfig.AppID
	secret := config.WeAppConfig.Secret
	CodeToSessURL := config.WeAppConfig.CodeToSessURL
	CodeToSessURL = strings.Replace(CodeToSessURL, "{appid}", appID, -1)
	CodeToSessURL = strings.Replace(CodeToSessURL, "{secret}", secret, -1)
	CodeToSessURL = strings.Replace(CodeToSessURL, "{code}", code, -1)

	resp, err := http.Get(CodeToSessURL)
	if err != nil {
		c.Data["json"] = &map[string]interface{}{
			"errNo": models.ErrorCode.ERROR,
			"msg":   err,
		}
		c.ServeJSON()
		return
	}

	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		c.Data["json"] = &map[string]interface{}{
			"errNo": models.ErrorCode.ERROR,
			"msg":   err,
		}
		c.ServeJSON()
		return
	}

	var data map[string]interface{}
	err = json.NewDecoder(resp.Body).Decode(&data)
	if err != nil {
		c.Data["json"] = &map[string]interface{}{
			"errNo": models.ErrorCode.ERROR,
			"msg":   err,
		}
		c.ServeJSON()
		return
	}

	if _, ok := data["session_key"]; !ok {
		c.Data["json"] = &map[string]interface{}{
			"errNo": models.ErrorCode.ERROR,
			"msg":   "session_key 不存在",
		}
		c.ServeJSON()
		return
	}
	// openID := data["openid"].(string)
	sessionKey := data["session_key"].(string)
	userInfoStr, err := tools.DecodeWeAppUserInfo(encryptedData, sessionKey, iv)
	fmt.Println(userInfoStr)
}

// SetWeAppUserInfo 设置小程序用户加密信息
func (c *UserController) SetPhone() {
	iv := c.GetString("iv")
	encryptedData := c.GetString("encryptedData")
	code := c.GetString("code")

	appID := config.WeAppConfig.AppID
	secret := config.WeAppConfig.Secret
	CodeToSessURL := config.WeAppConfig.CodeToSessURL
	CodeToSessURL = strings.Replace(CodeToSessURL, "{appid}", appID, -1)
	CodeToSessURL = strings.Replace(CodeToSessURL, "{secret}", secret, -1)
	CodeToSessURL = strings.Replace(CodeToSessURL, "{code}", code, -1)

	resp, err := http.Get(CodeToSessURL)
	if err != nil {
		c.Data["json"] = &map[string]interface{}{
			"errNo": models.ErrorCode.ERROR,
			"msg":   err,
		}
		c.ServeJSON()
		return
	}

	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		c.Data["json"] = &map[string]interface{}{
			"errNo": models.ErrorCode.ERROR,
			"msg":   err,
		}
		c.ServeJSON()
		return
	}

	var data map[string]interface{}
	err = json.NewDecoder(resp.Body).Decode(&data)
	if err != nil {
		c.Data["json"] = &map[string]interface{}{
			"errNo": models.ErrorCode.ERROR,
			"msg":   err,
		}
		c.ServeJSON()
		return
	}

	if _, ok := data["session_key"]; !ok {
		c.Data["json"] = &map[string]interface{}{
			"errNo": models.ErrorCode.ERROR,
			"msg":   "session_key 不存在",
		}
		c.ServeJSON()
		return
	}
	openID := data["openid"].(string)
	sessionKey := data["session_key"].(string)

	userInfoStr, err := tools.DecodeWeAppUserInfo(encryptedData, sessionKey, iv)
	fmt.Println(userInfoStr)

	if err != nil {
		c.Data["json"] = &map[string]interface{}{
			"errNo": models.ErrorCode.ERROR,
			"msg":   err,
		}
		c.ServeJSON()
		return
	}
	var user models.PhoneInfo
	if err := json.Unmarshal([]byte(userInfoStr), &user); err != nil {
		c.Data["json"] = &map[string]interface{}{
			"errNo": models.ErrorCode.ERROR,
			"msg":   err,
		}
		c.ServeJSON()
		return
	}

	// 将手机号更新到数据库中
	u := models.User{
		OpenId: openID,
		Phone:  user.PurePhoneNumber,
	}
	numCode, err := models.UpdateUserForPhone(&u)
	fmt.Println(numCode, err)
	// 异常处理
	if err != nil {
		c.Data["json"] = &map[string]interface{}{
			"errNo": models.ErrorCode.ERROR,
			"msg":   "failed",
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = &map[string]interface{}{
			"errNo": models.ErrorCode.SUCCESS,
			"msg":   "success",
			"data":  &user,
		}
	}
	c.ServeJSON()
}
